<template>
	<div>
		<div class="header">



			<!-- title="智能供佛系统" -->
			<van-nav-bar style="  background: linear-gradient(90deg, #41A9B7,#4fd4e2, #41A9B7);height: 5rem;line-height: 5rem;">

				<span class="title" slot="title">填写资料</span>

				<span style="font-size:1.5625rem ; color: white; font-weight: 500;" slot="right">
					<van-button type="primary" color="#348994" @click="back">&nbsp;返&nbsp;&nbsp;&nbsp;回&nbsp;</van-button>
				</span>
			</van-nav-bar>
		</div>


		<!-- /////////////////////////////////////////////////////////// -->
		<div class="content" >

			<!-- 二维码展示处 -->
			<div style="margin-top: 5rem;">
				<span style="font-size: 1.5rem;font-weight: bold;">使用微信扫码填写资料</span>
			</div>
			<div style="margin-top: 1rem">

				<van-count-down style="font-size: 1.1rem ; font-weight: bold; color: red; margin-bottom: 10px;" @finish="timeFinish"
				 :time="time" format="本次交易失效时间:	ss 秒" />

				<van-image width="20rem;" height="20rem" fit="contain" :src="QRCode" />

			</div>

			<div style="margin-top: 1.5rem;">


				<van-button icon="edit" @click="goGongfoStep0" style="width: 16rem;" size="large" color="#217a68" round type="info">本机输入</van-button>

			</div>




			<van-dialog v-model="dialogShowAdmin" title="管理员支付" @cancel="beforeClose()" :show-cancel-button="true"
			 :showConfirmButton="false" style="width: 37.5rem;">


				<div>
					<div style="margin: 1rem auto; ">
						<!-- <span style="font-size: 1.25rem;">请在10秒内完成操作</span> -->
					</div>

					<!-- xjpaytishiyu -->
					<van-image src="./images/cashcard.png" width="18.75rem" height="18.75rem" style="margin-bottom: 1rem;" />

					<div>
						<van-image src="./images/xjpaytishiyu.png" width="18.75rem" height="3.75rem" />
					</div>

				</div>
			</van-dialog>



		</div>
	</div>

</template>

<script>
	export default {


		data() {
			return {
				QRCode: "",
				isPay: false,
				phoneNumber: null,
				intervalId: 0,
				total_fee: 0,
				day: 0,
				ledList: [],
				dialogShowAdmin: false,
				cancelCard: false,
				out_trade_no: "",
				time: 60 * 1000 * 2






			}
		},
		methods: {


			back() {
			//	this.$router.go(-1);
			
			this.$router.push('gongfo');
			},

			timeFinish() {
				this.dialogShowAdmin = false;
				this.cancelCard = true; //取消键盘监听事件
				clearInterval(this.intervalId); //关闭订单轮询定时器
				this.$toast.fail("供佛超时！");
				this.$router.push("homePage");
			},

			goGongfoStep0() {
				//清除二维码订单状态轮询
				clearInterval(this.intervalId); //关闭定时器
				//
				this.$router.push({
					path: '/GongfoStep0_2',
					query: {
						total_fee: this.total_fee,
						ledList: this.ledList,
						day: this.day
					}
				});

			},
			beforeClose() {

			
				//
				this.$confirm('是否确认取消本次交易？(取消的订单可在订单管理中查看)', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
				
					this.cancelCard = true; //取消键盘监听事件
					clearInterval(this.intervalId); //关闭订单轮询定时器
					this.$router.push("homePage");
					this.$toast.fail({
						message: '本次订单已取消！'
					});
					console.log("支付取消了.............................");
				
				
				}).catch(() => {
					
					this.dialogShowAdmin=true;
					/* this.$message({
						type: 'info',
						message: '已取操作！'
					}); */
				
					/* this.$toast.success({
					 	message: '已取消操作！'
					 }); */
				});
				//


			},
			/* 管理员支付*/
			adminPay(card_no) {

				/* if (!this.checkPhoneNumber()) {
					return;
				} */
				this.dialogShowAdmin = true;
				//1吊起刷卡程序
				this.listenForCard();
				//限时刷卡时间
				/* setTimeout(()=>{
					
					this.dialogShowAdmin=false;
					this.cancelCard = true;//取消键盘监听事件
					clearInterval(this.intervalId); //关闭订单轮询定时器
					this.$toast.fail("非管理员-没有权限进行操作！");
					},1000*10); */

			},

			listenForCard() {

				this.cancelCard = false;
				let _this = this;
				let keyNumber = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
				let event_card_no = '';
				/* 监听键盘事件-读卡 */
				function fn(e) {
					//event_card_no='';

					for (let i = 0; i < 10; i++) {
						if (e.keyCode == keyNumber[i]) {
							event_card_no += i;
							break;
						} else if (e.keyCode == 13) {
							console.log(event_card_no);
							//event_card_no='';	
							document.removeEventListener("keydown", fn);
							console.log("移除了该事件");
							_this.doAdminPay(event_card_no);
							break;
						}


					}
				}

				document.addEventListener("keydown", fn);

				/* 查看是否需要关闭监听事件 */
				let cardInterval = setInterval(() => {
					console.log(this.cancelCard);
					if (this.cancelCard) {
						document.removeEventListener("keydown", fn);
						clearInterval(cardInterval);
					}
				}, 500)






			},

			getQRcode() {


			

				let total_fee = this.$route.query.total_fee;
				let ledList = this.$route.query.ledList;
				let day = this.$route.query.day;
				//这里的led和code微信code码冲突了，需额外处理
				let ledListStr = JSON.stringify(ledList).replace("[", "*").replace("]", "*");



				for (let i = 0; i < ledList.length; i++) {
					ledListStr = ledListStr.replace("code", "ledCode");
				}
				window.console.log("ledListStr--------------------------------------------->>", ledListStr);

				//生成唯一订单号 //可用于查询微信订单状态
				let out_trade_no = '';
				for (var i = 0; i < 4; i++) //4位随机数，用以加在时间戳后面。
				{
					out_trade_no += Math.floor(Math.random() * 10);
				}
				out_trade_no = new Date().getTime() + out_trade_no; //时间戳，用来生成订单号。
				window.console.log("out_trade_no========", out_trade_no);

				this.out_trade_no = out_trade_no;


				this.axios.get('https://xf.mianmianshi.com/URL_QRCode', { //
						responseType: 'arraybuffer', //注意返回类型
						params: {
							tid:this.$store.getters.getTempleData.tid|| localStorage.tid,
							total_fee: total_fee,
							ledListStr: ledListStr,
							day: day,
							out_trade_no: out_trade_no ,//唯一订单号
							type:localStorage.type||this.$store.getters.getTempleData.type

						}


					})
					.then((res) => {
						window.console.log("getQRCode", res);
						/* 处理图片 */
						this.QRCode = 'data:image/png;base64,' +
							btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
						//this.dialogShow = true;

						window.console.log(this.QRCode);


						//开始查询订单，判断用户支付状态
						this.intervalId = setInterval(() => {
							console.log("查询订单状态。。。。。。。。。。。。。。。。。。")
							if (this.isPay) {

								clearInterval(this.intervalId); //关闭定时器
							} else {
								this.isPaid(out_trade_no);
							}
						}, 1500);
						//


					})
					.catch(function(error) {
						console.log(error);
					});
			},

			isPaid(out_trade_no) {
				/* 查询订单状态，是否支付成功,支付成功则跳转 */
				this.axios.post('https://mianmianshi.com/cms/temple/client/findOder', {
						where: {
							oid: out_trade_no
						}
					})
					.then((res) => {
						console.log("payRes============================================", res)
						if (res.status == 200) {

							this.phoneNumber = res.data[0].telephone; //电话号码即为用户账号

							if (res.data[0].state == 1) { //支付成功 1添加订单，2获取用户信息，准备跳转用户中心
								this.isPay = true;


								this.goUserPage(); //跳转到用户页面
							} else if (res.data[0].state == 2) { //生成的未确认支付订单，这里需确认处理
								this.isPay = true;
								this.adminPay(); //管理员刷卡验证



							}


						}

					})
					.catch(function(error) {
						console.log(error);
					});
			},

			goUserPage() {

				///////////////////////////////////////////////////////////////////////
				//查询用户信息(购买人) ，添加到store
				this.axios.post('https://mianmianshi.com/cms/temple/client/findUser', {
						where: {
							phone_number: this.phoneNumber,
							tid: this.$store.getters.getTid
						}

					})
					.then((res) => {

						window.console.log("userRES=============================", res);
						if (res.data.id) {
							this.$store.commit("setUser", res.data);
						}

						const toast = this.$toast.loading({
							duration: 0, // 持续展示 toast
							forbidClick: true, // 禁用背景点击
							loadingType: 'spinner',
							message: '支付成功即将前往个人中心，倒计时 3 秒'
						});

						let second = 3;
						const timer = setInterval(() => {
							second--;
							if (second) {
								toast.message = `支付成功即将前往个人中心，倒计时 ${second} 秒`;
							} else {
								clearInterval(timer);
								this.$toast.clear();
								this.$router.push("consumer");
							}
						}, 1000);

					})
					.catch(function(error) {
						console.log(error);
					});
				//////////////////////////////////////////////////////////////////////
			},
			async doAdminPay(card_no) {
				//读到了卡数据，进行处理
				///////////////////////////////////////////////////////////////////////
				await this.axios.post('https://mianmianshi.com/cms/temple/client/findUser', {
						'where': {
							card_no: card_no,
							tid: this.$store.getters.getTid | localStorage.tid
						}
					})
					.then((res) => {
						//判断是不是该寺庙管理员
						if (res.data.identity == "ADMIN") {
							
							//刷卡回车到这里，是自动关闭键盘监听事件的
							//修改订单状态
							this.updateOrderState();



						} else { //其他卡号

							this.$toast.fail("非管理员-没有权限进行操作！");
							//this.dialogShowAdmin = false;
							this.listenForCard(); //如果不是则再次读取进行验证
							
						}

					})
					.catch(function(error) {
						console.log(error);
					});

				///////////////////////////////////////////////////////////////////////
			},

			async updateOrderState() {

				await this.axios.post('https://mianmianshi.com/cms/temple/client/updateOrder', {
						'where': {
							oid: this.out_trade_no
						}
					})
					.then((res) => {

						if (res.status == 200) { //状态修改完成，进入个人中心

							//修改led状态
							//updateLedIsprice//更新led状态
							this.axios.post('https://mianmianshi.com/cms/temple/client/updateLedIsprice', {
									ledList: this.ledList,
									isbright: 1

								})
								.then((res) => {
									if (res.status == 200) {

										this.$toast.success({
											message: '供佛成功！'
										});

										this.goUserPage();
									}
								})
								.catch((err) => {
									//console.log("失败了");
									console.log(err);
									alert("服务器繁忙，请稍后再试！");
								});


						}


					})
					.catch(function(error) {
						console.log(error);
					});
			}






		},

		created() {

			this.total_fee = this.$route.query.total_fee;
			this.ledList = this.$route.query.ledList;
			this.day = this.$route.query.day;

			this.getQRcode();
		},
		mounted() {

		},
		destroyed() {
			this.cancelCard = true;
			clearInterval(this.intervalId); //关闭定时器
		}

	}
</script>

<style>
	.xundeng {
		position: absolute;
		height: 100%;
		width: 100%;
		background: url(../../public/images/xundeng.png) no-repeat;
		background-size: 100% 100%;
	}
</style>
